Completed
Push — master ( 1b4532...54964d )
by Andres
01:14
created

angular.service(ꞌsavegameꞌ)   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
nc 4
dl 0
loc 11
rs 9.4285
nop 1
1
/* globals versionCompare, atob, btoa */
2
'use strict';
3
4
angular
5
  .module('game')
6
  .service('savegame', ['$state',
7
    'state',
8
    'data',
9
    'achievement',
10
    function ($state, state, data, achievement) {
11
      this.initSave = function () {
12
        state.player = {};
13
        versionControl();
14
        achievement.init();
15
        state.init();
16
        $state.go('matter');
17
      };
18
19
      this.load = function () {
20
        try {
21
          let storedPlayer = localStorage.getItem('playerStoredITE');
22
          // versionControl will catch an invalid player
23
          state.player = JSON.parse(storedPlayer);
24
          versionControl();
25
        } catch (err) {
26
          alert('Error loading savegame, reset forced.');
27
          this.initSave();
28
        }
29
      };
30
31
      function versionControl() {
32
        // delete saves older than this version
33
        if (state.player.version && versionCompare(state.player.version, '2.1.0') < 0) {
34
          state.player = {};
35
        }
36
        // we merge the properties of the player with the start player to
37
        // avoid undefined errors with new properties
38
        state.player = angular.merge({}, data.start_player, state.player);
39
        // append an id if it doesn't exist
40
        if (!state.player.id) {
41
          state.player.id = Math.random().toString().substring(3);
42
        }
43
      }
44
    }
45
  ]);
46